/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.cg.util;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.ant.DirectoryScanner;

public class ClassLoader
{
	private URLClassLoader loader;

	public ClassLoader(String... filePaths)
	{
		try
		{
			List<URL> list = new ArrayList<URL>();

			for(String filePath : filePaths)
			{
				File file = new File(filePath);

				if(file.exists())
				{
					URL url = file.toURI().toURL();
					list.add(url);
				}
			}

			URL[] urls = list.toArray(new URL[list.size()]);

			loader = new URLClassLoader(urls, getClass().getClassLoader());
		}
		catch(Exception e)
		{
			throw new RuntimeException(e);
		}
	}

	public Class<?> loadClass(String className)
	{
		try
		{
			return loader.loadClass(className);
		}
		catch(ClassNotFoundException cnfe)
		{
			throw new RuntimeException(cnfe);
		}
	}

	public String getClasspath()
	{
		StringBuilder sb = new StringBuilder();

		URL[] urls = loader.getURLs();

		for(int i = 0; i < urls.length; i++)
			sb.append(urls[i].toString()).append(";");

		return sb.toString();
	}

	public static void main(String[] args)
	{
		DirectoryScanner ds = new DirectoryScanner();
		ds.setBasedir("C:/lib");
		ds.setIncludes(new String[] { "*.jar" });

		ds.scan();

		String[] files = ds.getIncludedFiles();

		for(int i = 0; i < files.length; i++)
			files[i] = ds.getBasedir() + "/" + files[i];

		ClassLoader classLoader = new ClassLoader(files);

		Class<?> cls = classLoader.loadClass(
				"com.xyz.MyClass");

		System.out.println(cls.getName());
	}
}
